package cn.itcast.searchService.impl;
import cn.itcast.pojo.ItemDoc;
import cn.itcast.pojo.RequestParams;
import cn.itcast.searchService.SearchService;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.search.ItemClient;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {


    @Autowired
    RestHighLevelClient client;

    @Autowired
    ItemClient itemClient;

    @Override
    public PageDTO<ItemDoc> list(RequestParams param) {



        try {
            SearchRequest request = new SearchRequest("item");

            buildBasicQuery(param,request);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            return handleResponse(response);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 聚合搜索
     * @param param
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams param) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(param, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request,param);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");

            List<String> categoryAgg = getAggByName(aggregations, "categoryAgg");

            Map<String, List<String>> map = new HashMap<>();

            map.put("brand", brandAgg);

            map.put("category", categoryAgg);


            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<String> getAggByName(Aggregations aggregations,String names){

        Terms categoryAgg = aggregations.get(names);

        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = categoryAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    private void buildAggregation(SearchRequest request, RequestParams param) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
//        request.source().aggregation(AggregationBuilders.range("priceAgg")
//                .field("price")
//          )
    }

    /**
     * 自动补全
     * @param key
     * @return
     */
    @Override
    public List<String> suggestion(String key) {

        SearchRequest request = new SearchRequest("item");

        request.source().suggest(new SuggestBuilder().addSuggestion("mysugger",
                SuggestBuilders.completionSuggestion("suggestion").prefix(key)
                        .skipDuplicates(true)
                        .size(10)));
        //执行请求

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析相应

            Suggest suggest = response.getSuggest();

            CompletionSuggestion mysugger = suggest.getSuggestion("mysugger");

            List<String> list = new ArrayList<>();

            for (CompletionSuggestion.Entry.Option option : mysugger.getOptions()) {

                String TEXT = option.getText().toString();

//                System.out.println("建议字段"+TEXT);

                list.add(TEXT);
            }

            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void deleteById(Long id) {
        //根据id删除
        try {
            DeleteRequest request = new DeleteRequest("item",String.valueOf(id));
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行删除索引库数据失败");

        }
    }

    /**
     * es设置状态
     * @param arr
     */
    @Override
    public void setStatus(long[] arr) {
        long id = arr[0];
        long status = arr[1];

        //判断状态
        if (status == 1){
            //调用feign查询该用户并插入到es
            try {
                Item item  = itemClient.findItemById(id);

                ItemDoc doc = new ItemDoc(item);
                //将该数据添加
                IndexRequest request = new IndexRequest("item");
                String jsonString = JSON.toJSONString(doc);
                request.id(String.valueOf(doc.getId()));
                request.source(jsonString, XContentType.JSON);
                client.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (status == 2){
            //将该用户从es中删除
            deleteById(id);
        }



    }



    /**
     * 基本查询条件
     * @param param
     * @param request
     */
    public void buildBasicQuery(RequestParams param,SearchRequest request) {

        //设置分页
        request.source().from((param.getPage()-1)*param.getSize()).size(param.getSize());

        //创建复合查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //判断key是否有值并设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        if (StringUtils.isNotBlank(param.getKey())){
            boolQuery.must(QueryBuilders.matchQuery("all",param.getKey()));
            highlightBuilder.field("name");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            highlightBuilder.requireFieldMatch(false);
            request.source().highlighter(highlightBuilder);

        }else{
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //判断brand是否有值
        if (StringUtils.isNotBlank(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",param.getBrand()));
        }

        //判断category是否有值
        if (StringUtils.isNotBlank(param.getCategory())){
            boolQuery.filter(QueryBuilders.termQuery("category",param.getCategory()));
        }

        //判断price是否有值
        if (param.getMaxPrice()!=null && param.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lt(param.getMaxPrice()*100).gt(param.getMinPrice()*100));
        }
        //设置排序规则
        //判断排序条件
        switch (param.getSortBy()){
            case("sold"):
                request.source().sort("sold", SortOrder.DESC);
                break;
            case ("price"):
                request.source().sort("price", SortOrder.ASC);
                break;
        }

        request.source().query(boolQuery);


        //构建算分函数
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }
        );

        request.source().query(functionScoreQueryBuilder);
    }



    public PageDTO<ItemDoc> handleResponse(SearchResponse response){

        //处理响应请求
        SearchHits hits = response.getHits();

        //获取查询总条数
        long value = hits.getTotalHits().value;

        SearchHit[] DocArr = hits.getHits();

        List<ItemDoc> list = new ArrayList<>();

        if (DocArr.length!=0){

            for (SearchHit doc : DocArr) {
                String json = doc.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
                //获取高亮字段
                Map<String, HighlightField> highlightFields = doc.getHighlightFields();

                if (!CollectionUtils.isEmpty(highlightFields)){
                    HighlightField field = highlightFields.get("name");
                    if (field!= null){
                        String newName = field.getFragments()[0].toString();
                        itemDoc.setName(newName);
                    }
                }

                list.add(itemDoc);

            }
        }

         PageDTO<ItemDoc> pageDTO = new PageDTO<>();

        pageDTO.setTotal(value);

        pageDTO.setList(list);

        return pageDTO;
    }
}
